<template>
  <div>
    <h2>个人信息</h2>
    <el-form :model="form" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="form.adminName" disabled></el-input>
      </el-form-item>
      <el-form-item label="昵称">
        <el-input v-model="form.adminNickname"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.adminPassword" type="password"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <div class="avatar-upload-container">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:9093/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-error="handleAvatarError"
            :data="uploadData"
          >
            <div class="avatar-preview">
              <img v-if="form.adminProfilePictureSrc" :src="form.adminProfilePictureSrc" class="avatar-image" />
              <el-avatar v-else :src="defaultAvatar" class="avatar-image"></el-avatar>
            </div>
            <el-button size="small" type="primary" class="upload-button">选择文件</el-button>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-input v-model="form.createTime" disabled></el-input>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-input v-model="form.updateTime" disabled></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateInfo">保存信息</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

const form = ref({
  id: '',
  adminName: '',
  adminNickname: '',
  adminPassword: '',
  adminProfilePictureSrc: '',
  createTime: '',
  updateTime: ''
})

const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')

// 计算属性，用于上传时附加URL参数
const uploadData = computed(() => {
  return {
    url: form.value.adminProfilePictureSrc || ''
  }
})

const fetchAdminInfo = async () => {
  try {
    const adminId = sessionStorage.getItem("adminId")
    if (!adminId) {
      ElMessage.error('未找到管理员ID')
      return
    }

    const response = await request.get(`/user/getAdminInfo?id=${adminId}`)
    if (response.data.code === 200) {
      form.value = { ...response.data.data }
    } else {
      ElMessage.error(response.data.message || '获取信息失败')
    }
  } catch (error) {
    ElMessage.error('获取信息失败: ' + error.message)
  }
}

const updateInfo = async () => {
  try {
    // 创建一个不包含时间字段的更新对象
 // 创建与后端 AdminDto 类一致的数据结构
    const updateData = {
      id: form.value.id,
      username: form.value.adminName,
      nickname: form.value.adminNickname,
      password: form.value.adminPassword,
      avatarUrl: form.value.adminProfilePictureSrc
    }
    console.log('updateData', updateData.avatarUrl)
    const response = await request.put('/user/updateAdminInfo', updateData)
    if (response.data.code === 200) {
      ElMessage.success('信息更新成功')
      // 重新获取用户信息以更新时间字段
      fetchAdminInfo()
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败: ' + error.message)
  }
}

const handleAvatarSuccess = (response) => {
  // 假设后端返回格式为 {code: 200, data: {url: '图片地址'}}
  if (response.code === 200) {
    form.value.adminProfilePictureSrc = response.data
    console.log('头像上传成功:', form.value.adminProfilePictureSrc)
    ElMessage.success('头像上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleAvatarError = (error) => {
  ElMessage.error('头像上传失败: ' + error.message)
}

const beforeAvatarUpload = (rawFile) => {
  // 检查文件类型
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!')
    return false
  }
  // 检查文件大小 (限制为2MB)
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  return true
}

onMounted(() => {
  fetchAdminInfo()
})
</script>

<style scoped>
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  transition: border-color 0.3s;
}

.avatar-upload-container:hover {
  border-color: #409eff;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  border-radius: 50%;
  margin-bottom: 15px;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-button {
  margin-top: 10px;
}
</style>
